package edu.tyut.game.ui.community

import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import edu.tyut.game.GameApplication
import edu.tyut.game.R
import edu.tyut.game.databinding.FragmentCommunityBinding
import edu.tyut.game.logic.network.ServiceCreator
import edu.tyut.game.ui.person.PersonViewModel
import edu.tyut.game.utils.LogUtils
import edu.tyut.game.utils.StatusBarUtils

class CommunityFragment : Fragment() {

    private val tag = this::class.java.name

    private var _binding: FragmentCommunityBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private val viewModel by lazy {
        ViewModelProvider(this)[CommunityViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {


        _binding = FragmentCommunityBinding.inflate(inflater, container, false)
        val root: View = binding.root

        // 用户名、性别
        binding.username.text = GameApplication.loginUser?.username
        binding.gender.text = GameApplication.loginUser?.gender

        binding.send.setOnClickListener {
            PostFriendCircleActivity.actionStart(this.requireContext())
        }

        // =========== 观察者 =========
        // 发表评论
        viewModel.resComment.observe(viewLifecycleOwner){ res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true){
                LogUtils.d(tag, "评论发表成功: $isSuccess")
            }
        }
        // 查询评论
        // 删除评论
        viewModel.resDeleteComment.observe(viewLifecycleOwner){ res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true){
                LogUtils.d(tag, "评论删除成功：$isSuccess")
            }
        }
        // 评论点赞 + 1
        viewModel.resAddCommentLike.observe(viewLifecycleOwner){ res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true){
                LogUtils.d(tag, "评论点赞成功 + 1")
            }
        }
        // 评论点赞 - 1
        viewModel.resSubCommentLike.observe(viewLifecycleOwner){ res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true){
                LogUtils.d(tag, "评论取消点赞成功 - 1")
            }
        }
        // 查询朋友圈
        val layoutManager = LinearLayoutManager(context)
        binding.recyclerView.layoutManager = layoutManager
        viewModel.resFriendCircles.observe(viewLifecycleOwner){ res ->
            val friendCircles = res.getOrNull()
            friendCircles?.let {
                // 查询朋友圈
                LogUtils.d(tag, "查询朋友圈 $it")
                val adapter = FriendCircleAdapter(requireActivity(), it.toMutableList(), viewModel, this)
                // 嵌套
                binding.recyclerView.adapter = adapter
            }
        }
        // 排序
        var orderFlag = false
        binding.order.setOnClickListener {
            if (orderFlag) {
                viewModel.queryFriendCircle("ASC")
                Toast.makeText(requireContext(), "升序", Toast.LENGTH_LONG).show()
                binding.order.setImageDrawable(AppCompatResources.getDrawable(requireContext(), R.drawable.up))
            }else{
                viewModel.queryFriendCircle("DESC")
                Toast.makeText(requireContext(), "降序", Toast.LENGTH_LONG).show()
                binding.order.setImageDrawable(AppCompatResources.getDrawable(requireContext(), R.drawable.down))
            }
            orderFlag = !orderFlag
        }
        viewModel.queryFriendCircle("DESC")

        // 删除朋友圈
        viewModel.resDeleteFriendCircle.observe(viewLifecycleOwner){ res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true){
                LogUtils.d(tag, "朋友圈删除成功")
            }
        }

        // 朋友圈点赞 + 1
        viewModel.resAddFriendCircleLike.observe(viewLifecycleOwner){ res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true){
                LogUtils.d(tag, "朋友圈点赞 + 1")
            }
        }

        // 朋友圈点赞 - 1
        viewModel.resSubFriendCircleLike.observe(viewLifecycleOwner){ res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true){
                LogUtils.d(tag, "朋友圈点赞 - 1")
            }
        }
        // ============= 获取评论 ==============
        // viewModel.resComments.observe(viewLifecycleOwner) { res ->
        //     val contents = res.getOrNull()
        //     if (!contents.isNullOrEmpty()){
        //         LogUtils.d(tag, "${tag}, 评论展示: $contents")
        //     }
        // }
        // ====================================
        val url = "${ServiceCreator.BASE_URL}${GameApplication.loginUser!!.avatarPath}"
        LogUtils.d(tag, url)
        Glide.with(this.requireContext()).load(url).into(binding.iconImage)
        // ===========================
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    fun showComment(holder: FriendCircleAdapter.ViewHolder, fcId: Int){
        viewModel.queryComment(fcId)
        val layoutManager = LinearLayoutManager(context)
        holder.recyclerView.layoutManager = layoutManager
        viewModel.resComments.observe(viewLifecycleOwner) { res ->
            val contents = res.getOrNull()
            if (!contents.isNullOrEmpty()){
                LogUtils.d(tag, "评论展示: $contents")
                val adapter = CommentAdapter(requireContext(), contents.toMutableList(), viewModel, fcId)
                holder.recyclerView.adapter = adapter
            }
        }
    }
}